package com.maserb.monitor.dataCenter.communication;

import com.maserb.monitor.ApplicationUtils;
import com.maserb.monitor.dataCenter.communication.BaseNetPackageHandler;
import com.maserb.monitor.dataCenter.communication.EigenValueNetPackageHandler;
import com.maserb.monitor.dataCenter.communication.MonitorMessageProtocol;
import com.maserb.monitor.dataCenter.handler.WaveNetPackageHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class DataCenterServerHandler extends ChannelHandlerAdapter {

    BaseNetPackageHandler[] handlers;

    public DataCenterServerHandler() {
        handlers = new BaseNetPackageHandler[]{
                ApplicationUtils.getBean(EigenValueNetPackageHandler.class),
                ApplicationUtils.getBean(WaveNetPackageHandler.class)
        };
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 用于获取客户端发来的数据信息
        MonitorMessageProtocol body = (MonitorMessageProtocol) msg;
        if (handlers != null) {
            for (BaseNetPackageHandler handler : handlers) {
                if (handler.canHandle(body)) {
                    handler.handle(body);
                    break;
                }
            }
        }

//        // 会写数据给客户端
//        String str = "Hi I am Server ...";
//        MonitorMessageProtocol response = new MonitorMessageProtocol(str.getBytes().length, 2,
//                str.getBytes());
//        // 当服务端完成写操作后，关闭与客户端的连接
//        ctx.writeAndFlush(response);
        // .addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
